package org.ilead.iserve.service.impl;

import java.util.List;

import org.ilead.iserve.dao.ISystemMessageDAO;
import org.ilead.iserve.dao.IUserSystemMessageAssociateDAO;
import org.ilead.iserve.model.SystemMessage;
import org.ilead.iserve.model.UserSystemMessageAssociate;
import org.ilead.iserve.service.ISystemMessageService;

public class SystemMessageService implements ISystemMessageService {
	private ISystemMessageDAO systemMessageDAO;
	private IUserSystemMessageAssociateDAO userSystemMessageAssociateDAO;

	public void setSystemMessageDAO(ISystemMessageDAO systemMessageDao) {
		this.systemMessageDAO = systemMessageDao;
	}

	public void setUserSystemMessageAssociateDAO(
			IUserSystemMessageAssociateDAO userSystemMessageAssociateDAO) {
		this.userSystemMessageAssociateDAO = userSystemMessageAssociateDAO;
	}

	@Override
	public void addMessage(SystemMessage message) {
		systemMessageDAO.save(message);
	}

	@Override
	public List<SystemMessage> findByUserId(int userId) {
		List<SystemMessage> messageList = systemMessageDAO.findAll();
		List<UserSystemMessageAssociate> associateList = 
			userSystemMessageAssociateDAO.findByProperty(IUserSystemMessageAssociateDAO.USER_ID, userId);
		if(associateList == null || associateList.size() == 0)
			return messageList;
		
		return null;
	}

	@Override
	public void deleteMessage(int userId, int messageId) {
		UserSystemMessageAssociate associate = new UserSystemMessageAssociate();
		associate.setUserId(userId);
		associate.setMessageId(messageId);
		userSystemMessageAssociateDAO.delete(associate);
	}

	@Override
	public void updateMessageState(int userId, int messageId, int state) {
		UserSystemMessageAssociate associate = new UserSystemMessageAssociate();
		associate.setUserId(userId);
		associate.setMessageId(messageId);
		associate.setState(state);
		userSystemMessageAssociateDAO.attachDirty(associate);
	}
	
	@Override
	public void saveOrUpdateMessage(UserSystemMessageAssociate associate) {
		userSystemMessageAssociateDAO.attachDirty(associate);
	}

	@Override
	public int findUnReadCountByUserId(int userId) {
		List<SystemMessage> messageList = systemMessageDAO.findAll();
		List<UserSystemMessageAssociate> associateList = 
			userSystemMessageAssociateDAO.findByProperty(IUserSystemMessageAssociateDAO.USER_ID, userId);
		if(messageList == null || messageList.size() == 0)
			return 0;
		if(associateList == null || associateList.size() == 0)
			return messageList.size();
		
		return messageList.size() - messageList.size();
	}

	@Override
	public UserSystemMessageAssociate findByUserIdAndMessageId(int userId,
			int messageId) {
		UserSystemMessageAssociate asso = new UserSystemMessageAssociate();
		asso.setMessageId(messageId);
		asso.setUserId(userId);
		List<UserSystemMessageAssociate> list = userSystemMessageAssociateDAO.findByExample(asso);
		return list != null && list.size() > 0 ? list.get(0) : null;
	}

}
